import { createI18n } from "vue-i18n";
import zh from "./zh.json";
import en from "./en.json";

import elEnCn from "element-plus/es/locale/lang/en";
import elZhCn from "element-plus/es/locale/lang/zh-cn";

// 获取浏览器界面语言，默认语言
// https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/language
// let currentLanguage = navigator.language.replace(/-(\S*)/, '')
let currentLanguage = navigator.language.toLowerCase();
if (currentLanguage.startsWith("zh")) {
  if (!currentLanguage.endsWith("-cn")) {
    currentLanguage = "zh-cn"; // 默认为中国大陆的中文
  }
} else if (currentLanguage.startsWith("en")) {
  if (!currentLanguage.endsWith("-us")) {
    currentLanguage = "en-us"; // 默认为美国的英语
  }
}

// 如果本地缓存记录了语言环境，则使用本地缓存
const lsLocale = localStorage.getItem("locale") || "";
if (lsLocale) {
  currentLanguage = JSON.parse(lsLocale)?.curLocale;
}

const messages = {
  "en-us": {
    ...en,
    ...elEnCn
  },
  "zh-cn": {
    ...zh,
    ...elZhCn
  }
};

export const i18n = createI18n({
  legacy: false,
  locale: currentLanguage,
  fallbackLocale: "zh-cn",
  globalInjection: true,
  messages
});

export const langs = [
  { key: "zh", title: "中文" },
  { key: "en", title: "English" }
];

export const elLocaleMap = {
  "zh-cn": elZhCn,
  "en-us": elEnCn
};

export function safeT(key: string, fallback: string = ""): string {
  return i18n.global.te(key) ? i18n.global.t(key) : fallback;
}
